import { Client } from "@notionhq/client";
import { NotionToMarkdown } from "notion-to-md";

const notion = new Client({
  auth: import.meta.env.NOTION_API_KEY,
});

const databaseID = "a03a4671d365486b8d942933d62097a5";

export async function GET({ params, request }) {
  const responde = await notion.databases.query({
    database_id: databaseID,
  });

  const typedRespone = responde as unknown as NotionDB;

  // return new Response(JSON.stringify(typedRespone.results[0]));

  const posts = typedRespone.results.map((post) => {
    const {
      properties: {
        Title,
        description,
        slug,
        categories,
        thumbnail,
        publication_date,
      },
    } = post;
    return {
      id: post.id,
      title: Title.title.length > 0 ? Title.title[0].plain_text : '',
      description: description.rich_text.length > 0 ? description.rich_text[0].plain_text : '',
      slug: slug.rich_text.length ? slug.rich_text[0].plain_text : '',
      categories: categories.length > 0 ? categories.multi_select.map((item) => ({
        label: item.name,
        color: item.color,
      })) : [],
      tumnbnail: thumbnail.url,
      created_time: post.created_time,
      last_edited_time: post.last_edited_time,
      publication_date: publication_date.date ? publication_date.date.start : null,
    };
  });

  return new Response(JSON.stringify(posts));
}
